package com.aaa.zs.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

//非法字符过滤
@Component
public class IllegalCharFilter extends ZuulFilter {

    @Value("${illegal_char}")
   private String illegalChar;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        /**
         * 具体的过滤器的业务方法
         */
        System.out.println("进入到非法字符过滤器。。。。");
        //获取zuul中提供的上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
//        获取request
        HttpServletRequest request=requestContext.getRequest();
        //获取response对象
        HttpServletResponse response = requestContext.getResponse();
        //获取请求的参数名称集合 ?a=1&b=2&c=3&aa=11
        //parameterNames =[a,b,c,aa]
        Enumeration<String> parameterNames = request.getParameterNames();
        //解析配置的非法字符illegalCharArray[sb,nnd,tmd]
        String[] illegalCharArray = illegalChar.split(",");
        //循环遍历所有用户名称
        while(parameterNames.hasMoreElements()){
            //第一次a 第二次 b
            String parameterName = parameterNames.nextElement();
            //根据名称获取值
            String parameterValue = request.getParameter(parameterName);
            //判断里面是否含有非法字符
            for (String illegalChar : illegalCharArray) {
                if(parameterValue.toLowerCase().contains(illegalChar)){
                    //阻止程序继续运行
                    requestContext.setSendZuulResponse(false);
                    response.setCharacterEncoding("utf-8");
                    try {
                        response.sendError(HttpStatus.SC_FORBIDDEN,"你的请求中含有非法字符，不能访问");
                        return null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}
